import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

interface IUserItem {
  id: number;
  login: string;
  avatar_url: string;
  html_url: string;
}

interface IUserState {
  hasSearch: boolean;
  loading: boolean;
  userList: IUserItem[];
}

// 异步action
export const searchUserListAsync = createAsyncThunk(
  "user/searchUserList", // action名称，要求唯一
  async (keyword: string) => {
    const result = await axios.get(
      "https://api.github.com/search/users?q=" + keyword
    );
    return result.data.items.map((item: IUserItem) => {
      return {
        id: item.id,
        login: item.login,
        avatar_url: item.avatar_url,
        html_url: item.html_url,
      };
    });
  }
);

const userSlice = createSlice({
  name: "user",
  initialState(): IUserState {
    return {
      hasSearch: false,
      loading: false,
      userList: [],
    };
  },
  // 普通reducer：处理同步action的reducer函数 -> 自动生成同步action
  reducers: {},
  // 额外reducer：处理异步action的reducer函数
  extraReducers(builder) {
    builder
      // 异步action进行中
      .addCase(searchUserListAsync.pending, (state) => {
        console.log("异步action进行中");
        state.hasSearch = true;
        state.loading = true;
      })
      // 异步action执行成功
      .addCase(searchUserListAsync.fulfilled, (state, action) => {
        console.log("异步action执行成功");
        state.loading = false;
        state.userList = action.payload;
      })
      // 异步action执行失败
      .addCase(searchUserListAsync.rejected, () => {
        console.log("异步action执行失败");
      });
  },
});

export default userSlice.reducer;
